using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using UnityGameFramework.Runtime;

namespace DTFramework.UI
{
    public static class UIExtension
    {
        /// <summary>
        /// �ر�UI����
        /// </summary>
        public static void CloseUIForm(this UIComponent uiComponent, UGuiForm uiForm)
        {
            uiComponent.CloseUIForm(uiForm.UIForm);
        }

        public static IEnumerator FadeToAlpha(this CanvasGroup canvasGroup, float alpha, float duration)
        {
            float time = 0f;
            float originalAlpha = canvasGroup.alpha;
            while (time < duration)
            {
                time += Time.deltaTime;
                canvasGroup.alpha = Mathf.Lerp(originalAlpha, alpha, time / duration);
                yield return new WaitForEndOfFrame();
            }

            canvasGroup.alpha = alpha;
        }

        public static IEnumerator SmoothValue(this Slider slider, float value, float duration)
        {
            float time = 0f;
            float originalValue = slider.value;
            while (time < duration)
            {
                time += Time.deltaTime;
                slider.value = Mathf.Lerp(originalValue, value, time / duration);
                yield return new WaitForEndOfFrame();
            }
            slider.value = value;
        }

        /// <summary>
        ///  ��������ת��UGUI��Canvas Camera������ 
        /// </summary>
        /// <param name="root"></param>
        /// <param name="worldPos"></param>
        /// <param name="localPoint"></param>
        /// <returns></returns>
        public static bool WorldToUGUIPoint(this Canvas root, Vector3 worldPos, out Vector2 localPoint)
        {
            var screenPos = Camera.main.WorldToScreenPoint(worldPos);
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(root.transform as RectTransform, screenPos, null, out localPoint))
            {
                return true;
            }
            return false;
        }
    }
}
